/**
 * Created by LeungZ on 2016/10/16.
 */
import xterm from 'xterm';

class Detail {
    constructor($stateParams, $window, connection, $scope, podSrv, ctgNotification, $timeout) {
        "ngInject";

        this.dbCode = $stateParams.kDbCode;
        this.srvName = $stateParams.srvName;
        this.nodeIp = $stateParams.nodeIp;
        this.name = $stateParams.name;
        this.namesp = $stateParams.namesp;
        this.from = $stateParams.from;

        var term = new xterm(), winTimer = '';
        term.open(angular.element('#xterm').css('height', $window.innerHeight - 120)[0]);
        term.fit();

        $window.onresize = function () {
            $timeout.cancel(winTimer);
            winTimer = $timeout(function () {
                angular.element('#xterm').css('height', $window.innerHeight - 120)[0];
                term.fit();
            }, 50, false);
        };

        if (connection) {
            var socket = new WebSocket($window.location.protocol === 'https:' ? "wss://" : "ws://"
            + $window.location.host +
            '/ctg-imageconsole-web/ssh/terms.ws/' + connection.instanceId + '/' + this.dbCode + '/' + this.name);

            socket.onopen = function () {
                angular.element(term.textarea).on('keyup', function (e) {
                    if (socket.readyState === 1) {
                        socket.send(angular.toJson({
                            instanceId: connection.instanceId,
                            command: ((e.keyCode > 64 && e.keyCode < 91) || (e.keyCode > 47 && e.keyCode < 58)
                            || (e.keyCode > 185 && e.keyCode < 193) || (e.keyCode > 218 && e.keyCode < 223)
                            || e.keyCode == 32) ? e.key : '',
                            keyCode: ((e.ctrlKey && e.keyCode > 64 && e.keyCode < 91)
                            || ~[8, 9, 37, 38, 39, 40].indexOf(e.keyCode)
                            || (e.keyCode == 13 && angular.element('.terminal-cursor').parent().text().indexOf('#\u00A0exi') == -1)) ? e.keyCode : -1
                        }));
                    }
                })
            };
            socket.onmessage = function (ev) {
                term.write(ev.data.replace(/ \r/g, function (data, index) {
                    return index % 63 ? data : '';
                }));
            };

            socket.onerror = function () {
                term.off('key');
            };
            socket.onclose = function () {
                term.off('key');
            };

            $scope.$on('$destroy', function () {
                podSrv.closeConn(connection.instanceId).catch(function (data) {
                    ctgNotification.error("关闭终端有误. " + data.resultMsg);
                }).finally(function () {
                    socket.close();
                });
                $window.onresize = null;
            })
        }
    }
}
export default Detail